import 'dart:async';

import 'package:easy_image_viewer/easy_image_viewer.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:intl/intl.dart';

import '../../widget/dialog_container.dart';
import '../config/env_config.dart';
import '../const/app_color_const.dart';
import '../const/app_style_const.dart';
import '../type/empty_request_data_type.dart';

class CommonUtil {
  static bool debounceEnable = true;

  static isProduction() {
    //return const bool.fromEnvironment("dart.vm.product");
    return !kDebugMode;
  }

  static Map<String, dynamic> getEnvConfig() {
    return CommonUtil.isProduction()
        ? envProductionConfig
        : envDevelopmentConfig;
  }

  static void showToast(String msg) {
    SmartDialog.showToast(msg,
        displayTime: const Duration(milliseconds: 1500), usePenetrate: true);
  }

  static void showConfirmDialog(
    String tag,
    double dialogWidth,
    double dialogHeight,
    String content,
    Function confirmCallback,
    Function cancelCallback,
    String btnTxt,
    String btn2Txt,
  ) {
    SmartDialog.compatible.show(
      tag: tag,
      backDismiss: false,
      clickBgDismissTemp: false,
      isLoadingTemp: false,
      widget: DialogContainer(
          dialogHeight: dialogHeight,
          dialogWidth: dialogWidth == 0 ? 260 : dialogWidth,
          dialogPadding: 15,
          dialogHeaderCloseBtn: false,
          dialogHeaderBorderColor: transparentColor1,
          dialogFooterBorderColor: transparentColor1,
          dialogTitle: '提示',
          onDialogClose: () {
            SmartDialog.dismiss(tag: tag);
          },
          dialogBodyBuilder: (context) => Container(
                alignment: Alignment.topLeft,
                padding: const EdgeInsets.only(top: 5, bottom: 10),
                child: Text(content),
              ),
          dialogFooterBuilder: (context) => Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () {
                      confirmCallback(() => {SmartDialog.dismiss(tag: tag)});
                    },
                    child: Text('' != btnTxt ? btnTxt : "确认"),
                  ),
                  TextButton(
                    onPressed: () {
                      cancelCallback(() => {SmartDialog.dismiss(tag: tag)});
                    },
                    style: cancelBtnStyle,
                    child: Text('' != btn2Txt ? btn2Txt : "取消"),
                  ),
                ],
              )),
    );
  }

  static void showSingleConfirmDialog(
    String tag,
    double dialogHeight,
    String content,
    Function confirmCallback,
  ) {
    CommonUtil.showConfirmDialog(tag, 0, dialogHeight, content, confirmCallback,
        (cb) {
      cb();
    }, '', '');
  }

  static Function debounce(Function func, Duration? delay) {
    return () {
      if (debounceEnable) {
        func();
        debounceEnable = false;
        Future.delayed(delay ?? const Duration(milliseconds: 666), () {
          debounceEnable = true;
        });
      }
    };
  }

  static showImgViewer(context, int index, List<String> imgList) {
    if (imgList.isNotEmpty) {
      List<ImageProvider> list = [];
      for (var img in imgList) {
        if (img.isEmpty) {
          list.add(Image.asset("assets/images/not_found/not_img.png").image);
        } else {
          list.add(Image.network(img).image);
        }
      }

      MultiImageProvider multiImageProvider =
          MultiImageProvider(list, initialIndex: index);

      showImageViewerPager(context, multiImageProvider,
          useSafeArea: true,
          backgroundColor: transparentColor1,
          immersive: false,
          onPageChanged: (page) {},
          onViewerDismissed: (page) {});
    }
  }

  static bool isChinaPhoneLegal(String str) {
    return RegExp(
            '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[0-9])|(147,145))\\d{8}\$')
        .hasMatch(str);
  }

  static void textInputHide() {
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }

  static void cancelFocusNodes(context) {
    FocusScope.of(context).requestFocus(FocusNode());
  }

  static String formatMillisecondsSinceEpoch(int time, String format) {
    if (time == 0) {
      return '-';
    }
    return DateFormat(format, "zh_CN")
        .format(DateTime.fromMillisecondsSinceEpoch(time));
  }

  static String valueEmptyToStr(dynamic val, dynamic toStr) {
    String value = (val ?? toStr).toString();
    return value.isEmpty ? toStr : value;
  }

  static String valueEmptyToDefStr(dynamic val) {
    return valueEmptyToStr(val, '-');
  }

  static bool startWithHttp(String url) {
    return url.startsWith('http') || url.startsWith('https');
  }

  static int calcPageTotal(List<String> idList, int pageSize) {
    return idList.length % pageSize == 0
        ? idList.length ~/ pageSize
        : idList.length ~/ pageSize + 1;
  }

  static List<String> getSubIdList(
      int pageTotal, int currentPage, int pageSize, List<String> idList) {
    if (pageTotal == 0) {
      return [];
    }
    int start = pageSize * currentPage;
    int end = start + pageSize;
    if (end > idList.length - 1) {
      end = idList.length;
    }
    return idList.sublist(start, end);
  }

  static getDataList(int currentPage, int pageSize, int pageTotal,
      List<String> idList, Function query) {
    if (currentPage > pageTotal) {
      return CommonUtil.getEmptyRequestDataList();
    }
    List<String> list =
        CommonUtil.getSubIdList(pageTotal, currentPage - 1, pageSize, idList);

    if (list.isEmpty) {
      return CommonUtil.getEmptyRequestDataList();
    }
    return query(list);
  }

  static EmptyRequestDataType getEmptyRequestDataList() {
    return EmptyRequestDataType(
        {"code": "0000", "isSuccess": true, "msg": "success", "data": []});
  }
}
